import { getToken, setToken, getUserInfo as getUserInfoStore, setUserInfo } from '@/utils/webStorage'
import { loginApi, logoutApi, userInfoApi, menuApi } from '@/api/modules/app'
import router, { constantRoutes } from '@/router'
import { flattenTree } from '@/utils/dealData'
import Layout from '@/layout/index.vue'
// 动态加载路由，先引入静态文件
const modules = import.meta.glob('@/pages/**/*.vue')
const useUserStore = defineStore('user', {
    state: () => {
        return {
            token: getToken(),
            userInfo: getUserInfoStore(),
            routes: [],
            sidebarRouters: [],
            defaultRoutes: [],
            rewriteRoutes: [],
        }
    },
    actions: {
        login(data) {
            return new Promise(async (resolve, reject) => {
                loginApi(data)
                    .then(res => {
                        this.token = res.data.token ? res.data.token : undefined;
                        if (this.token) setToken(this.token)
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        getUserInfo() {
            return new Promise(async (resolve, reject) => {
                userInfoApi().then((res) => {
                    this.userInfo = res.data
                    // 本地化个人信息
                    setUserInfo(this.userInfo)
                    resolve(this.userInfo)
                })
            })
        },
        getMenu() {
            return new Promise(async (resolve, reject) => {
                menuApi().then((res) => {
                    const sidebarRoutes = filterAsyncRouter(res.data)
                    this.routes = res.data.map(item => item.name)
                    const rewriteRoutes = filterAsyncRouter(res.data, false, true)
                    this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
                    this.setDefaultRoutes(sidebarRoutes)
                    resolve(rewriteRoutes)
                })
            })
        },
        setSidebarRouters(routes) {
            this.sidebarRouters = routes
        },
        setDefaultRoutes(routes) {
            this.defaultRoutes = constantRoutes.concat(routes)
        },
        logout() {
            return new Promise((resolve, reject) => {
                logoutApi()
                    .then(res => {
                        resolve(res)
                    })
                    .catch(res => {
                        reject(res)
                    })
                    .finally(() => {
                        this.fedlogout()
                    })
            })
        },
        fedlogout() {
            clearStore()
            router.push('/login')
            window.location.reload()
        }
    }
})
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
            route.children = filterChildren(route.children)
        }
        if (route.component) {
            if (route.component == 'Layout') {
                route.component = Layout
            }
            if (typeof route.component ==='string' && route.component.includes('/')) {
                route.component = loadView(route.component)
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route['children']
            delete route['redirect']
        }
        return true
    })
}
function filterChildren(childrenMap, lastRouter = false) {
    var children = []
    childrenMap.forEach((el, index) => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach(c => {
                    c.path = el.path + '/' + c.path
                    if (c.children && c.children.length) {
                        children = children.concat(filterChildren(c.children, c))
                        return
                    }
                    children.push(c)
                })
                return
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path
            if (el.children && el.children.length) {
                children = children.concat(filterChildren(el.children, el))
                return
            }
        }
        children = children.concat(el)
    })
    return children
}
export const loadView = (view) => {
    let res;
    for (const path in modules) {
        const dir = path.split('pages/')[1].split('.vue')[0];
        if (dir === view) {
            res = () => modules[path]();
        }
    }
    return res;
}
export default useUserStore
